#include "elinput.h"
#include <QPaintEvent>
#include <QPainter>
#include "eltheme.h"

const int ElInput::Fixed_Width = 150;
const int ElInput::Fixed_Height = 32;
const int ElInput::Padding_Lr = 7;
const int ElInput::Padding_Tb = 3;

ElInput::ElInput(QWidget *parent)
    : ElComponent{parent}
{
    _lineEdit = new QLineEdit(this);
    _lineEdit->setFrame(false);
    _lineEdit->move(Padding_Lr, Padding_Tb);
    resize(Fixed_Width, Fixed_Height);
    _lineEdit->resize(Fixed_Width - 2 * Padding_Lr, Fixed_Height - 2 * Padding_Tb);
    _lineEdit->installEventFilter(this);
    setAttribute(Qt::WA_Hover);
    initPalette();
}

void ElInput::setEchoMode(EchoMode echoMode)
{
    _lineEdit->setEchoMode(echoMode);
}

bool ElInput::eventFilter(QObject *watched, QEvent *e)
{
    if (watched == _lineEdit) {
        if (e->type() == QEvent::FocusIn) {
            _palette.toggleColorGroup(ElPalette::Pressed);
            update();
        } else if (e->type() == QEvent::FocusOut) {
            _palette.toggleColorGroup(ElPalette::Normal);
            update();
        }
    }
    return ElComponent::eventFilter(watched, e);
}

void ElInput::paintEvent(QPaintEvent *e)
{
    QPainter painter(this);
    painter.setPen(_palette.color(ElPalette::Border));
    painter.setBrush(Qt::white);
    QRectF _rectf(this->rect());
    painter.drawRoundedRect(_rectf, height() / 8.0, height() / 8.0);
    e->accept();
}

void ElInput::enterEvent(QEvent *e)
{
    if (!isEnabled() || _palette.currentColorGroup() == ElPalette::Pressed) {
        e->accept();
        return;
    }
    _palette.toggleColorGroup(ElPalette::Entered); // Qt::WA_Hover is set so update automatically
    e->accept();
}

void ElInput::leaveEvent(QEvent *e)
{
    if (!isEnabled() || _palette.currentColorGroup() == ElPalette::Pressed) {
        e->accept();
        return;
    }
    _palette.toggleColorGroup(ElPalette::Normal); // Qt:WA_Hover is set so update automatically
    e->accept();
}

void ElInput::initPalette()
{
    _palette.setColor(ElPalette::Border, ThemeColor::textDisabledColor);
    _palette.setColor(ElPalette::Entered, ElPalette::Border, ThemeColor::infoColor);
    // pressed means focused in
    _palette.setColor(ElPalette::Pressed, ElPalette::Border, ThemeColor::primaryColor);
}
